import * as XLSX from 'xlsx'; // 导出excel
import { ElMessage } from 'element-plus';

/**
 * @description
 * @author ZhangYu
 * @date 03-04-2024
 * @param {*} tableData 需要导出的数组数据
 * @param {*} fileName 导出的名称
 */
const exportToExcel = (tableData: any, fileName: any) => {
    const worksheet = XLSX.utils.json_to_sheet(tableData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, fileName);
    XLSX.writeFile(workbook, fileName);
};

/**
 * @description
 * @author ZhangYu
 * @date 03-04-2024
 * @param {*} valOne 开始时间
 * @param {*} valTwo 结束时间
 * @param {*} hintTitle 开始时间必选提示
 * @param {*} hintInfo 日期违法提示
 */
const legalFun = async (valOne: any, valTwo: any, hintTitle: string, hintInfo: string) => {
    let isLegal = true;
    if(valTwo && !valOne){
        ElMessage({
            type: 'error',
            message: hintTitle,
        });
        isLegal = false;
    }
    if(valOne && valTwo){
        const dateMin = new Date(valOne).getTime();
        const dateMax = new Date(valTwo).getTime();
        if(dateMin > dateMax){
            ElMessage({
                type: 'error',
                message: hintInfo,
            });
            isLegal = false;
        }
    }
    return isLegal;
};

/**
 * @description
 * @author ZhangYu
 * @date 16-04-2024
 * @param {*} dateTime 需要拆分的日期时间
 */
const splitDate = (dateTime: any) => {
    if(dateTime){
        let dateArr: any = [];
        let getYear = dateTime.split(' ')[0].split('-')[0];
        let getMonth = dateTime.split(' ')[0].split('-')[1];
        let getDay = dateTime.split(' ')[0].split('-')[2];
        let getHour = dateTime.split(' ')[1].split(':')[0];
        let getMinute = dateTime.split(' ')[1].split(':')[1];
        let getSecond = dateTime.split(' ')[1].split(':')[2];
        dateArr.push(getYear,getMonth,getDay,getHour,getMinute,getSecond);
        return dateArr;
    }
}

/**
 * @description
 * @author ZhangYu
 * @date 20-04-2024
 * @param {*} cloneObj 深拷贝
 */
const deepClone = (cloneObj: any) => {
    if (cloneObj === null || typeof cloneObj !== 'object') {
        return cloneObj;
    }
 
    if (cloneObj instanceof Date) {
        return new Date(cloneObj.getTime());
    }
 
    if (cloneObj instanceof Array) {
        return cloneObj.reduce((arr: any, item: any, i: any) => {
            arr[i] = deepClone(item);
            return arr;
        }, []);
    }
 
    if (cloneObj instanceof Object) {
        return Object.keys(cloneObj).reduce((newObj, key) => {
            cloneObj[key] = deepClone(cloneObj[key]);
            return newObj;
        }, {});
    }
}

export { 
    exportToExcel,
    legalFun,
    splitDate,
    deepClone,
};